/*
 * AbstractCharNGramEst.java
 *
 * Created on November 8, 2007, 10:29 AM
 *
 */
package Estimator.NGramChar;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

/**
 *
 * @author Martin Haulrich
 */
abstract class AbstractCharNGramEst implements CharNGramEst {

    final int N;

    CharacterNGramCount ngrams;


    /** Constructor */
    public AbstractCharNGramEst(CharacterNGramCount ngrams, int N) {
        if (N > ngrams.getN()) {
            System.err.println("Warning: cannot set a N higher than the N in the CharacterNGram");
            System.err.println("Setting N to " + ngrams.getN());
            this.N = ngrams.getN();
        } else {
            this.N = N;
        }
        this.ngrams = ngrams;
    }


    @Override
    abstract public double getEstimate(String ngram);


    @Override
    public int getN() {
        return N;
    }


    @Override
    public void saveARPA(String filename) throws IOException {

        File f = new File(filename);
        f.delete();
        PrintWriter out = new PrintWriter(new FileWriter(filename));

        out.println("/data/");
        for (int n = 1; n <= N; n++) {
            out.println("ngram " + n + "=" + ngrams.getNDifferent(n));
        }
        out.println();
        for (int n = 1; n <= N; n++) {
            out.println("\\" + n + "-grams:");
            for (Iterator<String> it = ngrams.getNGrams(n).iterator(); it.hasNext();) {
                String ngram = it.next();
                double p = getEstimate(ngram);

                if (p != 0) {
                    out.println(p + "\t" + ngram);
                }
            }
            out.println();
        }
        out.close();
    }
}
